package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"

	"gitee.com/wang_cyi/TryEverything/promise"
	"gitee.com/wang_cyi/TryEverything/public"
)

type indexHandler struct{}

func (ih *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")

	html := `<doctype html>
        <html>
        <head>
          <title>Hello World</title>
        </head>
        <body>
        <p>
          Hello World
        </p>
        </body>
</html>`
	fmt.Fprintln(w, html)
}

//ResponseData is
type ResponseData struct {
	Code    string
	Content string
}

//ClientReqData is
type ClientReqData struct {
	Input  string `json:"input"`
	Output string `json:"output"`
}

//RtmpHandler is
type RtmpHandler struct {
	RtmpMap map[string]string
}

//ServeHTTP is
func (rtmp *RtmpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	w.Header().Set("Content-Type", "application/json")

	var input string
	var output string

	switch r.Method {
	case "GET":
		input = r.URL.Query().Get("input")
		output = r.URL.Query().Get("output")
		//log.Println("get", input, output)
		//无法解决参数有&分隔符
	case "POST":

		reqBody, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Fatal(err)
		}

		reqData := ClientReqData{}
		json.Unmarshal([]byte(reqBody), &reqData)
		input = reqData.Input
		output = reqData.Output
		//fmt.Println("http req Body =", input, output)

	}

	log.Println("http req = ", input, output)

	if len(output) == 0 {
		log.Println("output is null")
		responseDataExist := ResponseData{"-1", "output is null "}
		result, _ := json.Marshal(responseDataExist)
		w.Write(result)
		return
	}

	rtmp.RtmpMap["douyu"] = output
	var ff public.FfmPegTool

	//检查进程是否存在，如果存在就kill
	//ps -ef | grep javadeploy.jar | grep -v grep | awk '{print $2}' | xargs kill
	ff.KillByName("ffmpeg")

	time.Sleep(3 * time.Second)
	var ret bool = true
	var msg string
	if strings.Contains(input, ".txt") == true {
		if ff.Mp4ToRtmpTaskByConcat(input, output) < 0 {
			ret = false
			msg = "Mp4ToRtmpTaskByConcat"
		}
	} else {
		ret = ff.Mp4ToRtmp(input, output)
		msg = "ff.Mp4ToRtmp"
	}

	if ret == false {
		//output
		responseDataSuccess := ResponseData{"-100", msg}
		result, _ := json.Marshal(responseDataSuccess)

		w.Write(result)
	} else {
		//output
		responseDataSuccess := ResponseData{"100", "succed"}
		result, _ := json.Marshal(responseDataSuccess)

		w.Write(result)
	}

}

//ReadBookHandler is
type ReadBookHandler struct {
	messagesQue chan string
}

//ServeHTTP is
func (book *ReadBookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	var input string
	var output string
	switch r.Method {
	case "GET":
		input = r.URL.Query().Get("input")
		output = r.URL.Query().Get("output")
		log.Println("get", input, output)
		//无法解决参数有&分隔符
	case "POST":

		reqBody, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Fatal(err)
		}

		reqData := ClientReqData{}
		json.Unmarshal([]byte(reqBody), &reqData)
		input = reqData.Input
		output = reqData.Output

	}
	fmt.Println(input, output)
	log.Println(input, output)
	//发送数据
	task := promise.DailyTask{
		Code:    input,
		Param:   output,
		Queue:   book.messagesQue,
		RtmpMap: nil}
	task.Run()

	responseDataSuccess := ResponseData{"100", "succed"}
	result, _ := json.Marshal(responseDataSuccess)

	w.Write(result)

}

//LifeHandler 吃饭专心吃饭
type LifeHandler struct {
	LifeMap map[string]*promise.LifeData
	mConfig public.Config
}

//ServeHTTP is http 处理类
func (life *LifeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	var input string
	var data string

	switch r.Method {
	case "GET":
		input = r.URL.Query().Get("input")
		data = r.URL.Query().Get("data")
		//fmt.Println(input)
	}
	plan := promise.Plan{
		MConfig: life.mConfig,
	}

	var msg string
	//吃饭专心吃饭
	if strings.Contains(input, "eat") == true {
		eatData, _ := life.LifeMap["eat"]

		msg = plan.GetEatPromeData(eatData)

	}
	if strings.Contains(input, "sleep") == true {
		eatData, _ := life.LifeMap["sleep"]
		var plan promise.Plan
		msg = plan.GetOnTimeSleepPromeData(eatData)

	}
	if strings.Contains(input, "book") == true {
		eatData, _ := life.LifeMap["book"]
		var plan promise.Plan
		msg = plan.GetReadBookData(eatData)

	}

	//自动生成每周报告
	if strings.Contains(input, "week") == true {

		msg = plan.GenDailReport()
	}

	//自动生成每天日报
	if strings.Contains(input, "day") == true {
		msg = plan.GenDayworkReport()
	}

	//小时报告 插入mysql
	if strings.Contains(input, "hour") == true {
		fmt.Println(data)

		if len(data) > 3 {
			if true == public.DayMysql(data) {
				//msg = "ok"
			} else {
				msg = "error"
				msg += data
			}
		}

	}

	if len(msg) > 1 {
		plan.SendMsg(msg)
	}

	responseDataSuccess := ResponseData{"100", msg}
	result, _ := json.Marshal(responseDataSuccess)

	w.Write(result)

}
